package com.heima.tanhua.controller;

import com.heima.tanhua.commonResult.Result;
import com.heima.tanhua.dto.LocationDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import static com.heima.tanhua.constant.RedisConstant.GEO_KEY;

@RestController
@RequestMapping("/users/location")
public class LocationController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping
    public Result submit(@RequestBody LocationDto dto) {
        //添加坐标

        Point point = new Point(dto.getLongitude(), dto.getLatitude());
        redisTemplate.opsForGeo().add(GEO_KEY, point, dto.getUsername());
        return Result.success("成功");
    }
    @GetMapping
    public Result getRadius(Double longitude,Double latitude,Double distanceValue){
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                // 包含距离
                .includeDistance()
                // 包含经纬度
                .includeCoordinates()
                // 升序
                .sortAscending()
                // 最大查询数量
                .limit(10);
        //radius
        Point point=new Point(longitude,latitude);

        Distance distance=new Distance(distanceValue, Metrics.KILOMETERS);
        Circle circle=new Circle(point,distance);

        GeoResults<RedisGeoCommands.GeoLocation<String>> radius = redisTemplate.opsForGeo().radius(GEO_KEY, circle, args);
        return Result.success(radius);
    }
}
